//https://developers.arcgis.com/javascript/jssamples/map_switch_layer_on_zoom.html
//http://seiyria.github.io/bootstrap-slider/
//http://www.jqueryrain.com/demo/jquery-range-slider/
//http://handsontable.com/
var map, baseMap, baseMap2;
var isKmlClear = true;
$.holdReady(true);
require(["esri/map", "dojo/parser", "esri/Color", "dojo/_base/declare", 'dojo/domReady!'],
function(Map, parser) {
	parser.parse();

//	initTD();
//	baseMap = new TDTAnnoLayer();
	baseMap = new esri.layers.ArcGISTiledMapServiceLayer("http://linxi246.tunnel.qydev.com/hgp/services/014d2d5502d024248f104d2ce2a000e2/arcgis/tile");
	baseMap2 = new esri.layers.ArcGISTiledMapServiceLayer("http://linxi246.tunnel.qydev.com/hgp/services/014d2d5aa20424248f104d2ce2a00104/arcgis/tile");
	// baseMap = new esri.layers.ArcGISTiledMapServiceLayer("http://10.32.36.36/hgp/services/014d2d5502d024248f104d2ce2a000e2/arcgis/tile");
	// baseMap2 = new esri.layers.ArcGISTiledMapServiceLayer("http://10.32.36.36/hgp/services/014d2d5aa20424248f104d2ce2a00104/arcgis/tile");
	var centerPoints, extents, myZoom, groupId;
	dojo.connect(baseMap, "onLoad", function(results) {
		// 边界线
		var ringLayer = new esri.layers.GraphicsLayer();
		ringLayer.spatialReference = new esri.SpatialReference({
			wkid: 4490
		});
		ringLayer.initialExtent.setSpatialReference(4490);
		$.ajax({
			url: '../gis/AjaxUserAreaInfo.json?method=info',
			async: false
		}).done(function(data) {
			var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_NULL,
				new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID,
					new esri.Color("#CDB5CD"), 5
				));
			var graphics = [];
			var points = data.points.split(';');
			var dataIntArr = [];
			$.each(points, function(i, n) {
				dataIntArr.push(n.split(','));
			});
			centerPoints = data.centerPoint;
			extents = data.extent;
			extents.spatialReference = new esri.SpatialReference({
				wkid: 4490
			});
			myZoom = data.zoom;

			var polygon = new esri.geometry.Polygon();
			polygon.addRing(dataIntArr);
			var graphic = new esri.Graphic(polygon, symbol);

			ringLayer.add(graphic);
			graphics.push(graphic);
		});
		map = new esri.Map("map", {
			center: centerPoints,
			zoom: myZoom,
			logo: false,
			slider: false,
			sliderPosition: 'bottom-right'
		});
		var groupId = getCookie("groupId");
		var mapCenter = new esri.geometry.Point(centerPoints[0], centerPoints[1], {
			"wkid": 4490
		});
		map.centerAndZoom(mapCenter, myZoom);
		map.addLayer(baseMap);
		map.addLayer(baseMap2, 1);
		if (groupId != 1) {
			map.addLayer(ringLayer, 2);
		}
		$.map.layer = new esri.layers.GraphicsLayer();
		$.map.layer.spatialReference = new esri.SpatialReference({
			wkid: 4490
		});
		$.map.layer.initialExtent.setSpatialReference(4490);

		$.map.txtLayer = new esri.layers.GraphicsLayer();
		$.map.txtLayer.spatialReference = new esri.SpatialReference({
			wkid: 4490
		});
		$.map.txtLayer.initialExtent.setSpatialReference(4490);

		$.map.valLayer = new esri.layers.GraphicsLayer();
		$.map.valLayer.spatialReference = new esri.SpatialReference({
			wkid: 4490
		});
		$.map.valLayer.initialExtent.setSpatialReference(4490);

		$.map.dzxLayer = new esri.layers.GraphicsLayer();
		$.map.dzxLayer.spatialReference = new esri.SpatialReference({
			wkid: 4490
		});
		$.map.dzxLayer.initialExtent.setSpatialReference(4490);

		$.map.dzmLayer = new esri.layers.GraphicsLayer();
		$.map.dzmLayer.spatialReference = new esri.SpatialReference({
			wkid: 4490
		});
		$.map.dzmLayer.initialExtent.setSpatialReference(4490);

		map.addLayer($.map.layer, 3);
		map.addLayer($.map.txtLayer, 4);
		map.addLayer($.map.valLayer, 5);
		map.addLayer($.map.dzxLayer, 6);
		map.addLayer($.map.dzmLayer, 7);

		$.map.createMarkerSymbol = function() {
			var markerSymbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 8,
				new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color(
						'#0000ff'), 1), new dojo.Color('#0000ff'));
			return markerSymbol;
		}

		$.map.reExtent = function(isClear) {
			if (isClear) {
				$.map.layer.clear();
				$.map.txtLayer.clear();
				$.map.valLayer.clear();
				$.map.dzxLayer.hide();
				$.map.dzmLayer.hide();
				map.graphics.clear();

				// 清空所有表格的行选中发色样式
				$('table').find('.tableTrColor').removeClass('tableTrColor');
			}
			$('#clearBtn').trigger('click');
			var esriExtent = new esri.geometry.Extent(extents);
			map.centerAndZoom(mapCenter, myZoom);
		}

		map.on('extent-change', function(evt) {
			if ($("#stcdShow").is(':checked') == true) {
				if (evt.lod.level >= 7) {
					$.map.txtLayer.show();
					$.map.valLayer.hide();
				} else if (5 >= evt.lod.level) {
					$.map.txtLayer.hide();
					$.map.valLayer.hide();
				} else {
					$.map.txtLayer.hide();
					$.map.valLayer.show();
				}
				$.map.layer.show();
			} else {
				$.map.txtLayer.hide();
				$.map.valLayer.hide();
			}
		});

		// 操作面板 tab 操作事件
		$('#panelTabs,#rainPanelTabs a[data-toggle="tab"]').on('show.bs.tab', function(e) {
			var $_body = $('body');
			var targetPanelName = $(e.target).attr('aria-controls');
			var tmpTargetPanelName = targetPanelName;
			var relatedTargetPanelName = $(e.relatedTarget).attr('aria-controls');
			$("#stcdShow").prop("checked", true);
			$("#visoLineShow").prop("checked", false);

			if (relatedTargetPanelName == 'rain' || relatedTargetPanelName == 'downRain' || relatedTargetPanelName == 'evaporation') {
				var childerPanelName;
				if (relatedTargetPanelName == 'downRain' || relatedTargetPanelName == 'evaporation') {
					childerPanelName = relatedTargetPanelName;
					relatedTargetPanelName = 'rain';
				} else {
					childerPanelName = $('#rain').find('.nav-tabs .active a').attr('aria-controls');
				}
				relatedTargetPanelName += '_' + childerPanelName;
			}
			if (targetPanelName == 'rain' || targetPanelName == 'downRain' || targetPanelName == 'evaporation') {
				var childerPanelName;
				if (targetPanelName == 'downRain' || targetPanelName == 'evaporation') {
					childerPanelName = targetPanelName;
					targetPanelName = 'rain';
				} else {
					childerPanelName = $('#rain').find('.nav-tabs .active a').attr('aria-controls');
				}
				targetPanelName += '_' + childerPanelName;
			}
			if (targetPanelName == 'rain_downRain') {
				$('#sqLegend').show();
			} else {
				$('#sqLegend').hide();
			}

			var otherLayers = $.extend(true, {}, {
				layerGraphics: $.map.layer.graphics,
				txtLayerGraphics: $.map.txtLayer.graphics,
				valLayerGraphics: $.map.valLayer.graphics
			});
			$_body.data(relatedTargetPanelName, otherLayers);
			var storeLayers = $_body.data(targetPanelName);

			$.map.reExtent(true);

			if (storeLayers) {
				var layerGraphics = storeLayers.layerGraphics;
				var txtLayerGraphics = storeLayers.txtLayerGraphics;
				var valLayerGraphics = storeLayers.valLayerGraphics;

				$.each(layerGraphics, function(index, item) {
					$.map.layer.add(item);
					$.map.txtLayer.add(txtLayerGraphics[index]);
					$.map.valLayer.add(valLayerGraphics[index]);
				});
			} else {
				var headChar = tmpTargetPanelName.charAt(0).toUpperCase();
				var bodyStr = tmpTargetPanelName.substr(1);
				$('#query' + headChar + bodyStr + 'Btn').trigger('click');
			}
		});
		// 操作按钮导出事件
		$('.panel-export').on('click', function() {
			var csvDatas = $(this).parents('.form-inline').find('.panel-table').data('csvDatas');
			exportToCsv(csvDatas);
		});



		// 控制点击地图图标点，弹出的窗口
		$.map.makeWindow = function(stnm, stcd, callType) {
			var pageName = (callType == 'layerRain' ? 'rain' : callType) + '.html?t' + new Date().getTime();
			var tabNames;
			var winContent = $('#windowContent');
			windowInit(winContent, callType);

			var url = '../gis/StationScreen.json?method=getStationInfo&stcd=' + stcd;
			var target = $('#windowDialogInfo');
			var relatedTarget = $('#baseInfo', winContent);

			var title = stnm + '[' + stcd + ']';
			// 基本信息
			if (relatedTarget) {
				$.buildDialog({
					$_this: winContent,
					target: target,
					title: title,
					modal: true,
					width: 'auto',
					height: 'auto',
					relatedTarget: relatedTarget,
					url: url,
					stcd: stcd + '_baseInfo',
					callBuildData: buildWinBaseInfo
				});
			}
			url = '../gis/ReservoirScreen.json?method=getRSVRFCCH&stcd=' + stcd;
			relatedTarget = $('#rsvrfcchReservoir', winContent);
			// 水库防洪指标单击事件
			if (relatedTarget) {
				$.buildDialog({
					$_this: winContent,
					target: target,
					title: title,
					modal: true,
					width: 600,
					height: 260,
					relatedTarget: relatedTarget,
					url: url,
					stcd: stcd + '_reservoir',
					callBuildData: buildReservoirRsvrfcch
				});
			}
			url = '../gis/RiverScreen.json?method=getRVFCCH&stcd=' + stcd;
			relatedTarget = $('#rsvrfcchRiver', winContent);
			// 河道防洪指标单击事件
			if (relatedTarget) {
				$.buildDialog({
					$_this: winContent,
					target: target,
					title: title,
					modal: true,
					width: 600,
					height: 300,
					relatedTarget: relatedTarget,
					url: url,
					stcd: stcd + '_river',
					callBuildData: buildRiverWinRsvrfcch
				});
			}

			var mainTabs = $('#winTabs li', winContent);
			var activeTab, notActiveTab;
			mainTabs.each(function(i, n) {
				var item = $(n);
				if (item.hasClass('active')) {
					activeTab = item.find('a');
				} else {
					notActiveTab = item.find('a');
				}
			});

			var showTabPanel = $('#' + activeTab.attr('aria-controls'), winContent);
			showTabPanel.data('stcd', stcd).data('stnm', stnm).data('callType', callType);

			var tabPanel = $('#' + notActiveTab.attr('aria-controls'), winContent);
			tabPanel.data('stcd', stcd).data('stnm', stnm).data('callType', callType);
			// 显示窗口，并注册查询事件、实例化时间控件
			showWindow(showTabPanel);

			$.buildDialog({
				$_this: null,
				target: winContent,
				title: title,
				modal: true,
				width: 800,
				height: 560,
				close: function() {
					$('#day,#hour', winContent).removeData('isload');
					$(this).dialog('destroy');
				}
			});
		}


		$('#winTabs a[data-toggle="tab"]').on('show.bs.tab', function(e) {
			var showTabPanel = $('#' + $(e.target).attr('aria-controls'));
			var target = showTabPanel.find('.dataPanel ul .active');
			checkExportShow(target);

			// 显示窗口，并注册查询事件、实例化时间控件
			showWindow(showTabPanel);
		});

		// 判断切换时是否显示导出按钮
		$('.dataPanel a[data-toggle="tab"]').on('show.bs.tab', function(e) {
			checkExportShow($(e.target).parent());
		});

		function checkExportShow(target) {
			var btn = $('#exportCsvBtn');
			if (target.hasClass('haveExport')) {
				btn.show();
			} else {
				btn.hide();
			}
		}

		// 导出按钮
		var exportCsvBtn = $('#exportCsvBtn');
		// 注册导出按钮单击事件
		exportToCsvByBtn($('#windowContent'));
		$.buildDialog = function(params) {
			var close = params.close,
				$_this = params.$_this,
				title = params.title,
				modal = params.modal,
				width = params.width,
				height = params.height,
				relatedTarget = params.relatedTarget,
				url = params.url,
				stcd = params.stcd,
				target = params.target,
				callBuildData = params.callBuildData;
			var inner = function() {
				close = close ? close : function() {
					$(this).dialog('destroy');
				}
				var widthHeight = {};
				if (width != 'auto' && height != 'auto') {
					widthHeight.width = width;
					widthHeight.height = height;
				}
				var position = {};
				if ($_this != null) {
					position.position = {
						my: "center",
						at: "center",
						of: $_this.parents('.ui-widget')
					};
				}
				var option = $.extend({}, {
					resizable: false,
					show: true,
					title: title,
					modal: modal,
					close: close,
					open: function() {
						var widget = $(this).dialog('widget');
						var formPoint = $($(this).dialog("option", "position").of[0]);
						var parentZIndex = parseInt(formPoint.css('z-index'));
						var modal = $(this).dialog('option', 'modal');
						if (modal) {
							widget.prev('.ui-widget-overlay').css('z-index', ++parentZIndex);
						}
						widget.css('z-index', ++parentZIndex);

						// 去除选中边框
						widget.find('a,input,button').css('outline', 'none');
					}
				}, widthHeight, position);
				target.dialog(option);
			}
			if (relatedTarget == undefined) {
				inner();
			} else {
				relatedTarget.off('click');
				relatedTarget.on('click', function() {
					target.find('table *').remove();
					var showInfo = target.data(stcd);
					if (showInfo) {
						target.find('table').append(showInfo);
						inner();
					} else {
						$.get(url, function(data) {
							showInfo = callBuildData(data);
							target.find('table').append(showInfo);
							target.data(stcd, showInfo.html());
							inner();
						});
					}
				});
			}
		}
			// 地图点的单击事件
		jQuery.map.layer.on('click', mapClick);
		// 地图点选中的单击事件(调用江苏地图服务时map.graphics为null)
		map.graphics.on('click', mapClick);

		function mapClick(e) {
			var attr = e.graphic.attributes;
			var callType = attr.callType;
			$.map.makeWindow(attr.stnm, attr.stcd, callType);
		}

		var dateTimePicker = {
			language: 'zh-CN',
			weekStart: 1,
			todayBtn: 1,
			autoclose: 1,
			todayHighlight: 1,
			startView: 2,
			minView: 2,
			forceParse: 0
		}

		$('.panel-body .form_date').datetimepicker($.extend(dateTimePicker, {
			pickerPosition: "bottom-left"
		}));
		$('.dialogWindow .form_date').datetimepicker(dateTimePicker);

		$.holdReady(false);
	});
});